//
//  OnePicModeView.m
//  XRmenu
//
//  Created by shengchao yang on 11-11-25.
//  Copyright 2011年 foxhis. All rights reserved.
//

#import "OnePicModeView.h"
#import "UIDeviceHelper.h"

#define kTagOfPreRemoveImgV 5300
#define duration1 0.5f
@interface OnePicModeView(Private)
-(void) setDishSelected;
-(void) setLabelValue;
-(void) displayDishImg;
-(void) refreshDishplay;
-(void) nextPage:(BOOL) type;
-(void) previousPage:(BOOL) type;
-(void) autoTest;
@end

@implementation OnePicModeView
-(id) initWithStyle:(NSString*)stylename DishSubViewName:(NSString*)vname{
    self = [super initWithStyle:stylename DishSubViewName:vname];
    if (self) {       
        if ([self viewWithTag:kTagOfStartBT]) {
            UIButton *btn =(UIButton *) [self viewWithTag:kTagOfStartBT];             
            [btn.titleLabel setFont:[UIFont fontWithName:@"Arial" size:20.0f]];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [btn setBackgroundImage:[UIImage imageWithContentsOfFile:[XRmenuPublic getGeneralSkinImg:@"bt_detail.png"]] forState:UIControlStateNormal];
            [btn setTitle:loc(@"详细") forState:UIControlStateNormal];
            [self addSubview:btn];
        }
        if ([self viewWithTag:kTagOfStartBT+1]) {
            UIButton *btn =(UIButton *) [self viewWithTag:kTagOfStartBT+1]; 
            [btn.titleLabel setFont:[UIFont fontWithName:@"Arial" size:20.0f]];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [btn setBackgroundImage:[UIImage imageWithContentsOfFile:[XRmenuPublic getGeneralSkinImg:@"bt_order.png"]] forState:UIControlStateNormal];
            [btn setTitle:loc(@"点单") forState:UIControlStateNormal];
            [self addSubview:btn];
        }
        
        [self add1fingerLeftSwipe];
        [self add1fingerRightSwipe];
        [self add1fingerTopSwipe];
        [self add1fingerDownSwipe];
    }
    return self;
}
-(void) autoTest{
    [self nextPage:YES];//只有在测试的时候用
}
#pragma mark 数据更新
//=========================================================== 
// UpdateModeViewDataWithPluPlu
// 更新大图模式显示的内容
// 通过DisplayModeView被MainView调用
//===========================================================
-(void) UpdateModeViewDataWithPluPlu{    
    //显示当前选中的菜品图片
    if([APPSESSION.pluPlus count] > 0 && [self viewWithTag:kTagOfStartImgV]){        
        //显示当前图片
        [self displayDishImg];        
        [self setLabelValue]; //设置菜名和单价
        [(UIButton *) [self viewWithTag:kTagOfStartBT] setHidden:NO];
        [(UIButton *) [self viewWithTag:kTagOfStartBT+1] setHidden:NO];
        [(UILabel *) [self viewWithTag:kTagOfStartLabel] setHidden:NO];
        [(UILabel *) [self viewWithTag:kTagOfStartImgV+3] setHidden:NO];
    }
    else{
        [(UIImageView*)[self viewWithTag:kTagOfStartImgV] setImage:nil];
        [(UIButton *) [self viewWithTag:kTagOfStartBT] setHidden:YES];
        [(UIButton *) [self viewWithTag:kTagOfStartBT+1] setHidden:YES];
        [(UILabel *) [self viewWithTag:kTagOfStartLabel] setHidden:YES];
        [(UILabel *) [self viewWithTag:kTagOfStartImgV+3] setHidden:YES];
    }
    [self setDishSelected];
}
//设置选中打钩图片左上角
-(void) setDishSelected{
    if ([self viewWithTag:kTagOfStartImgV+2]) {
        if (APPSESSION.currentPluPlu.rsToDishOrder != nil) {
            [self viewWithTag:kTagOfStartImgV+2].hidden=NO;
        }else{
            [self viewWithTag:kTagOfStartImgV+2].hidden=YES;
        }
    }
}
//设置菜名和单价
-(void) setLabelValue{    
    if ([self viewWithTag:kTagOfStartLabel]) {//菜名+单价
        UILabel *lbl=(UILabel *)[self viewWithTag:kTagOfStartLabel];
        NSString* unit=JsonFiled(APPSESSION.currentPluPlu.ppUnits);
        NSString* price  = [NSString stringWithFormat:@"%@%0.2f",[APPSESSION.allconfig getStringValueAtPath:@"System Config/currency"],[APPSESSION.currentPluPlu.ppPrice floatValue]];
        if ([APPSESSION.currentPluPlu.ppPrice floatValue]==0) {
            price=loc(@"时价");
        }
        lbl.numberOfLines=3;
        [lbl setText:[NSString stringWithFormat:@"%@\r\n%@/%@",JsonFiled(APPSESSION.currentPluPlu.ppNames),price,unit]];
    }
}

#pragma mark 重载button处理方法
-(void) buttonClicked:(id)sender{
	NSInteger bid = [sender tag];
	if (bid == (kTagOfStartBT + 0)) {
        [APPSESSION playSoundOnEvent:[XRmenuPublic getGeneralSkinImg:@"buttonClicked.caf"]];
        postN(kMessage_RootView_PhotoPopoverViewDisplay);
	}
    else if (bid == (kTagOfStartBT + 1)) {     
        [APPSESSION playSoundOnEvent:[XRmenuPublic getGeneralSkinImg:@"buttonClicked.caf"]];
        //1.插入点单数据
        XRmenuError *outErr=nil;
        [XRmenuCoreData insertNewDishOrder:APPSESSION.currentPluPlu Error:&outErr];
        
        [self setDishSelected];//设置选中状态
        //2.界面上更新我的点单数量
        postN(kMessage_MainView_MyOrderNumberChanged);
	}
}

#pragma mark 重载手势方法
//往下翻，看后面的内容
- (void)handleSwipeTop:(UISwipeGestureRecognizer *)recognizer {
    [self nextPage:YES];
}
//往上翻，看前面的内容
- (void)handleSwipeDown:(UISwipeGestureRecognizer *)recognizer {    
    [self previousPage:YES];
}
//看后面(右)的内容
- (void)handleSwipeLeft:(UISwipeGestureRecognizer *)recognizer {
    [self nextPage:NO];
}
//看前面(左)的内容
- (void)handleSwipeRight:(UISwipeGestureRecognizer *)recognizer {
    [self previousPage:NO];
}

/////////////////////////////test function start/////////////////////////////////////
//证明白屏问题是由于播放声音文件没有释放句柄所造成的!
-(void) displayDishImg1{
    static int index = 0;
    NSLog(@"availableMemory:[%f] MB index=%d",[[UIDevice currentDevice] availableMemory], index);
    
    [APPSESSION playSoundOnEvent:[XRmenuPublic getGeneralSkinImg:@"trashDish.caf"]];//问题的原因所在!如果屏蔽掉此句就没问题
    
    //显示当前图片
    NSString *imgFile = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"png"];
    UIImage *img = [UIImage imageWithContentsOfFile:imgFile];
    [(UIImageView *)[self viewWithTag:kTagOfStartImgV] setImage:img];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.1f];
    [UIView setAnimationCurve: UIViewAnimationCurveEaseIn];
    [UIView setAnimationTransition: UIViewAnimationTransitionCurlUp forView:self cache: YES];
    [UIView setAnimationDelegate:self];
	[UIView setAnimationDidStopSelector:@selector(displayDishImg1)];
    [UIView commitAnimations];//这句是执行
    index++;
}
/////////////////////////////test function end/////////////////////////////////////

//显示当前菜品图片信息
-(void) displayDishImg{
//    APPSESSION.currentBatchNo++;
//    NSLog(@"availableMemory:[%f] MB _NO.%d",[[UIDevice currentDevice] availableMemory],APPSESSION.currentBatchNo);
    
//    //方法一：重新实例化一个UIImageView
//    //移除老的imageview
//    if ([self viewWithTag:kTagOfStartImgV]) {
//        UIImageView *tempImgV=(UIImageView *)[self viewWithTag:kTagOfStartImgV];
//        tempImgV.image=nil;
//        [tempImgV removeFromSuperview];
//    }
//    //重新生成新的imageview
//    CGRect imgVframe = CGRectOffset(CGRectFromString(@"{{0, 0}, {710, 640}}"), self.bounds.origin.x, self.bounds.origin.y);
//    UIImageView *imgV=[[UIImageView alloc] initWithFrame:imgVframe];
//    [imgV setTag:kTagOfStartImgV];
//    [self addSubview:imgV];
//    [imgV release];
//    //以下四个控件防止被遮盖(注意后两个的顺序)
//    [self addSubview:(UILabel *) [self viewWithTag:kTagOfStartImgV+2]];
//    [self addSubview:(UIButton *) [self viewWithTag:kTagOfStartBT]];
//    [self addSubview:(UIButton *) [self viewWithTag:kTagOfStartBT+1]];
//    [self addSubview:(UILabel *) [self viewWithTag:kTagOfStartImgV+3]];
//    [self addSubview:(UILabel *) [self viewWithTag:kTagOfStartLabel]];

    //方法二：重复使用UIImageView
    //显示当前图片
    XRmenuError* error = nil;    
    UIImage *img=getDishImg(APPSESSION.currentPluPlu.ppPluPluId,error);//菜品图片
    [(UIImageView *)[self viewWithTag:kTagOfStartImgV] setImage:img];
}
//翻页动画完成后的刷新
-(void) refreshDishplay{
    [self setLabelValue]; //设置菜名和单价
    [self setDishSelected];//设置选中状态
    //通知主界面修改右边tableview的选中状态
    postN(kMessage_MainView_SelectMainViewPluPlu);
}
//查看下一页
-(void) nextPage:(BOOL) type{
    if ([APPSESSION.pluPlus count] == 0) {
        return;
    }
    if (![self viewWithTag:kTagOfStartImgV]) {
        return;
    }
    //判断是否需要改变小类数组
    if (APPSESSION.currentPluIndex + 1 >= [APPSESSION.pluPlus count] && //条件一：当前小类的最后一个菜品
        APPSESSION.currentSortIndex + 1 < [APPSESSION.pluSorts count]) {//条件二：不是最后一组小类
        NSDictionary *infos1 = [NSDictionary dictionaryWithObjectsAndKeys:num(APPSESSION.currentSortIndex+1), @"newSortIndex", nil];
        postNWithInfos(kMessage_MainView_SelectNextPluSort, nil, infos1);
    }
    
    if (APPSESSION.currentPluIndex + 1 >= [APPSESSION.pluPlus count]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:loc(@"提示")
                                                        message:loc(@"最后一道菜")
                                                       delegate:self 
                                              cancelButtonTitle:loc(@"确定")
                                              otherButtonTitles:nil];    
        [alert show];     
        [alert release];
    }
    else{
        [APPSESSION playSoundOnEvent:[XRmenuPublic getGeneralSkinImg:@"trashDish.caf"]];
        [APPSESSION updateCurrentPluIndex:APPSESSION.currentPluIndex + 1];
        
        [self displayDishImg];
        [self refreshDishplay]; 
        
        if (type) {
            [UIView beginAnimations:@"flipping view" context:nil];
            [UIView setAnimationDuration:duration1];
            [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
            [UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self cache:YES];
            [UIView commitAnimations];
        }else{
            CATransition *animation = [CATransition animation];
            animation.duration = duration1;
            animation.timingFunction = UIViewAnimationCurveEaseInOut;
            animation.fillMode = kCAFillModeForwards;
            animation.type = kCATransitionPush;
            animation.subtype = kCATransitionFromRight; 
            [self.layer addAnimation:animation forKey:@"animation"];
        }
//        [self performSelector:@selector(autoTest) withObject:nil afterDelay:0.1f]; //测试自动连续翻页
    }
}
//查看上一页
-(void) previousPage:(BOOL) type{
    if ([APPSESSION.pluPlus count] == 0) {
        return;
    }
    if (![self viewWithTag:kTagOfStartImgV]) {
        return;
    }
    
    //判断是否需要改变小类数组
    if (APPSESSION.currentPluIndex <= 0 && //条件一：当前小类的第一个菜品
        APPSESSION.currentSortIndex > 0) { //条件二：不是第一组小类
        NSDictionary *infos1 = [NSDictionary dictionaryWithObjectsAndKeys:num(APPSESSION.currentSortIndex-1), @"newSortIndex", nil];
        postNWithInfos(kMessage_MainView_SelectNextPluSort, nil, infos1);
    }
    
    if(APPSESSION.currentPluIndex <= 0){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:loc(@"提示")
                                                        message:loc(@"第一道菜")
                                                       delegate:self 
                                              cancelButtonTitle:loc(@"确定")
                                              otherButtonTitles:nil];
        [alert show];     
        [alert release];
    }
    else{
        [APPSESSION playSoundOnEvent:[XRmenuPublic getGeneralSkinImg:@"trashDish.caf"]];
        [APPSESSION updateCurrentPluIndex:APPSESSION.currentPluIndex - 1];
        
        [self displayDishImg];
        [self refreshDishplay]; 
        
        if (type) {
            [UIView beginAnimations:@"flipping view" context:nil];
            [UIView setAnimationDuration:duration1];
            [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
            [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self cache:YES];
            [UIView commitAnimations];
        }else{
            CATransition *animation = [CATransition animation];
            animation.duration = duration1;
            animation.timingFunction = UIViewAnimationCurveEaseInOut;
            animation.fillMode = kCAFillModeForwards;
            animation.type = kCATransitionPush;
            animation.subtype = kCATransitionFromLeft; 
            [self.layer addAnimation:animation forKey:@"animation"];
        }
    }
}
@end